//
//  LTY_MVViewController.m
//  MooMusic
//
//  Created by 守护神 on 15/10/22.
//  Copyright © 2015年 wjy. All rights reserved.
//

#import "LTY_MVViewController.h"
// 把自定义的每日一发的头文件导入
#import "LTY_DayTableViewCell.h"
// 导入MVPlay的头文件
#import "LTY_MVPlayViewController.h"
// 导入分类的头文件
#import "LTY_ClassViewController.h"
// 导入NetWork头文件
#import "NetWork.h"
// 导入每日一发mdoel的头文件
#import "LTY_MVDayModel.h"
// 导入自定义collectonview的头文件
#import "LTY_MVCollectionViewCell.h"
// 导入MVCollectionModel的头文件
#import "LTY_MVCollecTionModel.h"

// 协议传值 第四步:  签订协议
@interface LTY_MVViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, SecondVCDelegate>

@property (nonatomic, strong)LTY_ClassViewController *classVC;
@property(nonatomic,assign)BOOL isUpLoading;
@property(nonatomic,assign)NSInteger nextCursor;
@property (nonatomic, assign)NSInteger collectionNextCursor;
// 设置一个NSInteger类型的数据 用来判断是"最热" 还是 "最新"
// 设置一个NSINteger类型的数据 用来判断order的类别
@property (nonatomic, assign)NSInteger hotOrnew;
// 设置一个NSINteger类型的数据 用来判断id的类别
@property (nonatomic, assign)NSInteger ID;
// 设置一个BOOL值来判断划过去之后就不请求数据了
@property (nonatomic, assign)BOOL collectionBool;


// 设置一个数据源
@property (nonatomic, strong)NSMutableArray *MVDayArray;
// 设置一个用来存放collection 上model的数据源
@property (nonatomic , strong)NSMutableArray *MVCollectionArray;
// 设置一个用来存放mvList的数据源
@property (nonatomic, strong)NSMutableArray *mvListArray;
// 设置一个用来存放tableview上的mvList上的数据源
@property (nonatomic, strong)NSMutableArray *TabMvList;

@end

static NSString *const cellInderer = @"cellInderer";
static NSString *const collection = @"collection";
// 定义一个标识 来判断请求的是哪页数据
NSInteger Value;

@implementation LTY_MVViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.MVDayArray = [NSMutableArray array];
        self.MVCollectionArray = [NSMutableArray array];
        self.mvListArray = [NSMutableArray array];
        self.TabMvList = [NSMutableArray array];
    }
    
    return self;
}

#pragma mark -- 返回按钮
- (void)BackAction
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // UIButton *AllButton = (UIButton *)[self.view viewWithTag:200];
    self.classVC = [[LTY_ClassViewController alloc] init];
    
    // 协议传值 第五步: 指定代理人
    self.classVC.delegate = self;
    
    __block UIView *view = self.view;
    __block NSInteger vcInteger = self.hotOrnew;
    __block NSInteger vcID = self.ID;
    __block NSInteger vcNextCursor = self.collectionNextCursor;
    __block NSMutableArray *vcArr = self.MVCollectionArray;
    __block LTY_MVViewController *vc = self;
    // 4. 实现Block回调
    self.classVC.sendBlock = ^(NSString *string, NSInteger order, NSInteger newCont){
        UIButton *tempBut = (UIButton *)[view viewWithTag:200];
        [tempBut setTitle:string forState:UIControlStateNormal];
        
        // 清空数组 重新请求数据
        [vcArr removeAllObjects];
        
        // "最热" 还是 "最新"
        vcInteger = order;
        // type 的类型
        vcID = newCont;
        // 设置初始值为1  就是页数
        vcNextCursor = 1;
        // 请求数据
        [vc getCollectionViewData];
        
    };


    
}

// 协议传值 第六步: 实现方法
- (void)sendValue:(NSString *)value sendOrder:(NSNumber *)order sendId:(NSNumber *)contID
{
    UIButton *tempButton = (UIButton *)[self.view viewWithTag:200];
    [tempButton setTitle:value forState:UIControlStateNormal];
    
//    // 设置order
    self.hotOrnew = [order integerValue];
//    // 设置id
    self.ID = [contID integerValue];
    
    // 清空数组 重新请求数据
    [self.MVCollectionArray removeAllObjects];
    // 设置初始值为1  就是页数
    self.collectionNextCursor = 1;
    // 请求数据
    [self getCollectionViewData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始值为1
    self.nextCursor = 1;
    self.collectionNextCursor = 1;
    // 进入的时候先是"最新"的页面 把order设置成1
    self.hotOrnew = 1;
    // 进入的时候先是"全部"的页面 id为0
    self.ID = 0;
    
    self.title = @"MV";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBarTintColor:COLOR(22, 88, 240, 1.0)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(BackAction)];
    
    // 创建视图
    [self creatMVView];
    // 添加头部控件
    [self addHeader];
    // 添加尾部控件
    [self addFooter];
    [self addFooterCollection];
    
    // Do any additional setup after loading the view.
}

// 获取collectionview上的数据
- (void)getCollectionViewData
{
    // 最新的测试接口
    // http://api.dongting.com/song/video/type/0?order=1&page=1&size=12&app=ttpod&v=v8.0.1.2015091618
    
    
    // 页数
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", self.collectionNextCursor];
    // 最新/最热
    NSString *HotAndNew = [NSString stringWithFormat:@"%ld", self.hotOrnew];
    // id
    NSString *newID = [NSString stringWithFormat:@"%ld", self.ID];
    
    // 替换完成后的接口
    NSString *str = [NSString stringWithFormat:urlMVclassString, newID, HotAndNew, pageNumber];
    
    NSLog(@"++++++  %@", str);
    
    // 网络请求
    [NetWork networkGETRequestWithURL:str Paramater:nil ResultBlock:^(id result) {
       //NSLog(@"result ===== %@", result);
        NSMutableArray *dataArray = [NSMutableArray array];
        dataArray = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in dataArray) {
            LTY_MVCollecTionModel *mdoel = [[LTY_MVCollecTionModel alloc] init];
            [mdoel setValuesForKeysWithDictionary:dic];
            [self.MVCollectionArray addObject:mdoel];

            // 判断类是不是NULL
            id d = [dic valueForKey:@"mvList"];
            if (![d isKindOfClass:[NSNull class]]) {
            
            if ([[dic valueForKey:@"mvList"] count] == 0 || [[dic objectForKey:@"mvList"] isEqual:[NSNull class]]) {
                [self.mvListArray addObject:@"http://otmv.alicdn.com/new/mv_1_5/dc/81/dcb63ada5a14ccbb320a6bd772b07481.mp4?k=de676de0a05f7818&t=1446116309"];
            }else{
                [self.mvListArray addObject:[[[dic valueForKey:@"mvList"] objectAtIndex:0] valueForKey:@"url"]];
            }
        
            }
            
        }
        
        
        if (self.MVCollectionArray.count > 0) {
             // 刷新collectionView
            [CollectionView reloadData];
        }
        
        // 下拉刷新停止
        [CollectionView footerEndRefreshing];
        // 自动加1
        self.collectionNextCursor = self.collectionNextCursor + 1;
        
        
    }];
    
    
}


#pragma mark --上拉加载collectionview数据更多
- (void)addFooterCollection
{
    //    __unsafe_unretained typeof(self) vc = self;
    // __block: 表示在 block 中的修改对于 block 外也是有效地
    __block LTY_MVViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [CollectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        NSLog(@"上拉加载更多，开始网络请求更多数据");
        vc.isUpLoading = YES;
        //用afn加载更多的数据
        [vc getCollectionViewData];
        
    }];
}






// 获取数据
- (void)getMVData:(NSInteger)nextCursor
{
    NSString *tempStr = [NSString stringWithFormat:@"%ld", self.nextCursor];
    NSString *mvString = [MVDayString stringByReplacingOccurrencesOfString:@"%@" withString:tempStr];
    NSLog(@"mvString = %@", mvString);
    [NetWork networkGETRequestWithURL:mvString Paramater:nil ResultBlock:^(id result) {
        //NSLog(@"+_+_+_+ %@", result);
        NSMutableArray *dataArr = [NSMutableArray array];
        dataArr = [result objectForKey:@"data"];
        
        // 存放model
        for (NSDictionary *dic in dataArr) {
            LTY_MVDayModel *modle = [[LTY_MVDayModel alloc] init];
            [modle setValuesForKeysWithDictionary:dic];
            [self.MVDayArray addObject:modle];
            
            // 判断类是不是NULL
            id d = [dic valueForKey:@"mvList"];
           // 方法1
            if ([d isEqual:[NSNull null]] || [[dic objectForKey:@"mvList"] count] == 0) {
                [self.TabMvList addObject:@"http://otmv.alicdn.com/new/mv_1_5/dc/81/dcb63ada5a14ccbb320a6bd772b07481.mp4?k=de676de0a05f7818&t=1446116309"];
            }else{
                // 把tablview上的播放的url存到一个数据源里
                [self.TabMvList addObject:[[[dic objectForKey:@"mvList"] objectAtIndex:0] valueForKey:@"url"]];
            }
            
        // 方法2
//            if (![d isKindOfClass:[NSNull class]] || [[dic objectForKey:@"mvList"] count] == 0){
//                // 把tablview上的播放的url存到一个数据源里
//                [self.TabMvList addObject:[[[dic objectForKey:@"mvList"] objectAtIndex:0] valueForKey:@"url"]];
//            }else{
//                [self.TabMvList addObject:@"http://otmv.alicdn.com/new/mv_1_5/dc/81/dcb63ada5a14ccbb320a6bd772b07481.mp4?k=de676de0a05f7818&t=1446116309"];
//            }

        }
        
    
        if (self.MVDayArray.count > 0) {
            // 刷新tableview
            [DayTableview reloadData];
        }
        
        
        //让自动下拉刷新停止
        [DayTableview headerEndRefreshing];
        [DayTableview footerEndRefreshing];
        
        // 自动加1
        self.nextCursor = self.nextCursor + 1;
        
        // 请求数据结束的时候使tableview的线显示
        DayTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        
    }];
}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    // __block: 表示在 block 中的修改对于 block 外也是有效地
    __block LTY_MVViewController *vc = self;
    
    // 添加下拉刷新头部控件
    [DayTableview addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        
        vc.isUpLoading = NO;//下拉
        //在block块里实现afn数据请求，一定要写在这里
        // 请求数据
        [vc getMVData:vc.nextCursor];
        
        
        NSLog(@"下拉刷新，开始网络请求第一页数据");
        
        
        
        
    }];
    
#pragma mark  --自动刷新(一进入程序就下拉刷新)
    [DayTableview headerBeginRefreshing];
}


#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    // __block: 表示在 block 中的修改对于 block 外也是有效地
    __block LTY_MVViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [DayTableview addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        NSLog(@"上拉加载更多，开始网络请求更多数据");
        vc.isUpLoading = YES;

        //用afn加载更多的数据
        [vc getMVData:vc.nextCursor];
        
    }];
}



// 创建视图
- (void)creatMVView
{
    seg = [[UISegmentedControl alloc] initWithItems:@[@"每日一发", @"MV分类"]];
    seg.frame = CGRectMake(0, 64, SCREENWIDTH, 40);
    seg.selectedSegmentIndex = 0;
    seg.tintColor = [UIColor orangeColor];
    // 绑定事件
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:seg];
    
    
    ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64 + 40, SCREENWIDTH, SCREENHEIGHT - seg.frame.size.height)];
    ScrollView.backgroundColor = [UIColor whiteColor];
    ScrollView.contentSize = CGSizeMake(SCREENWIDTH * 2 , 0);
    ScrollView.showsHorizontalScrollIndicator = NO;
    ScrollView.bounces = NO;
    ScrollView.delegate = self;
    // 是否滚动(能否滚动)
    ScrollView.scrollEnabled = YES;
    // 是否分页滚动(滚动条被等分成几段)
    ScrollView.pagingEnabled = YES;
    // 添加到父视图上
    [self.view addSubview:ScrollView];
    
    
    DayTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - 104) style:UITableViewStylePlain];
    DayTableview.backgroundColor = [UIColor whiteColor];
    DayTableview.delegate = self;
    DayTableview.dataSource = self;
    DayTableview.tag = 100001;
    // 创建的时候使tableview的线隐藏
    DayTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [DayTableview registerClass:[LTY_DayTableViewCell class] forCellReuseIdentifier:cellInderer];
    [ScrollView addSubview:DayTableview];
    
#pragma mark -- button and segment
    UIButton *allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake(10 + SCREENWIDTH, 10, 70, 30);
    allButton.backgroundColor = [UIColor clearColor];
    [allButton setTitle:@"全部" forState:UIControlStateNormal];
    [allButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    allButton.tag = 200;
    [allButton addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [ScrollView addSubview:allButton];
    
    newSegment = [[UISegmentedControl alloc] initWithItems:@[@"最热", @"最新"]];
    newSegment.frame = CGRectMake(SCREENWIDTH * 2 - 100, 10, 80, 30);
    newSegment.selectedSegmentIndex = 1;
    newSegment.tintColor = [UIColor blueColor];
    // 绑定事件
    [newSegment addTarget:self action:@selector(newSegment:) forControlEvents:UIControlEventValueChanged];
    [ScrollView addSubview:newSegment];
    
    
#pragma mark -- UICollectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // item大小 (宽  高)
    flowLayout.itemSize = CGSizeMake(SCREENWIDTH / 2 - 40, 160);
    // 最小的行间距 (垂直于滚动方向的是一行)
    flowLayout.minimumLineSpacing = 25;
    // 最小的列间距  cell的大小 section的缩进 共同来决定的item之间的距离
    flowLayout.minimumInteritemSpacing = 10;
    // section的缩进 (上 左 下 右)
    flowLayout.sectionInset = UIEdgeInsetsMake(25, 25, 25, 25);
    
    CollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(SCREENWIDTH, 50, SCREENWIDTH, SCREENHEIGHT - 150) collectionViewLayout:flowLayout];
    
    CollectionView.backgroundColor = [UIColor whiteColor];
    
    CollectionView.delegate = self;
    CollectionView.dataSource = self;
    
    // 注册item样式
    [CollectionView registerClass:[LTY_MVCollectionViewCell class] forCellWithReuseIdentifier:collection];
    
    [ScrollView addSubview:CollectionView];
    
    
    
}

#pragma mark -- collectionview
// section 的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

// 每个section中的item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.MVCollectionArray.count > 0) {
        return self.MVCollectionArray.count;
    }else{
        return 0;
    }
    
}

// item重用池
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LTY_MVCollectionViewCell *collectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:collection forIndexPath:indexPath];
    
    collectionCell.backgroundColor = [UIColor whiteColor];
    // 把model传递给自定义cell
    if (self.MVCollectionArray.count > 0) {
        collectionCell.model = [self.MVCollectionArray objectAtIndex:indexPath.item];
    }
    
    
    return collectionCell;
    
}

// collectionView点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"section = %ld, item = %ld", indexPath.section, indexPath.row);
    NSLog(@"跳转到每日一发的视频播放页面!");
    LTY_MVPlayViewController *playVC = [[LTY_MVPlayViewController alloc] init];
    UINavigationController *playNaVC = [[UINavigationController alloc] initWithRootViewController:playVC];
    // 把MV链接取出来
    NSString *playString = [self.mvListArray objectAtIndex:indexPath.row];
    playVC.playString = playString;
    [self presentViewController:playNaVC animated:YES completion:^{
        
        
    }];
    
    
}



//#pragma mark -- UICollectionViewDelegateFlowLayout



#pragma mark -- Tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.MVDayArray.count > 0) {
        return self.MVDayArray.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LTY_DayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInderer];
    
    if (self.MVDayArray.count > 0) {
        cell.model = [self.MVDayArray objectAtIndex:indexPath.row];
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSLog(@"跳转到每日一发的视频播放页面!");
    LTY_MVPlayViewController *playVC = [[LTY_MVPlayViewController alloc] init];
    UINavigationController *playNaVC = [[UINavigationController alloc] initWithRootViewController:playVC];
    NSString *playString = [self.TabMvList objectAtIndex:indexPath.row];
    playVC.playString = playString;
    [self presentViewController:playNaVC animated:YES completion:^{
        
        
    }];
}


#pragma mark - 按钮随之变动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    //如果滑动背景,按钮随之变动
    if (scrollView == ScrollView) {
        for (int i = 0; i < 2; i++) {
            if (ScrollView.contentOffset.x == SCREENWIDTH * i) {
                seg.selectedSegmentIndex = i;
            }
        }
    }
    
    // 当偏移量是一个屏幕宽度的时候 就请求collectionview的数据
    Value = scrollView.contentOffset.x / SCREENWIDTH;
    if (Value == 1 && !self.collectionBool) {
        // 改变布尔值属性 下回再拉就不请求数据了
        self.collectionBool = !self.collectionBool;
        [self getCollectionViewData];
    }
    
   
    
    
}

#pragma mark - 分段控制器方法
- (void)segAction:(UISegmentedControl *)Segment
{
    ScrollView.contentOffset = CGPointMake(Segment.selectedSegmentIndex * SCREENWIDTH, 0);

}

#pragma mark -- button触发的方法
- (void)buttonAction
{
    NSLog(@"button触发的方法");
    // 创建controllerVC是用属性创建的 在viewwillAppear上创建的
    [self.navigationController pushViewController:self.classVC animated:YES];
}

#pragma mark -- newSegment触发的方法
- (void)newSegment:(UISegmentedControl *)NewSegment
{
    NSLog(@"最新 最热触发的方法");
    if (NewSegment.selectedSegmentIndex == 1) {
        // 先清空原来的数组
        [self.MVCollectionArray removeAllObjects];
        // 最新
        self.hotOrnew = 1;
        // 页数的初始值再设置为1
        self.collectionNextCursor = 1;
        [self getCollectionViewData];
    }else{
        // 先清空原来的数组
        [self.MVCollectionArray removeAllObjects];
        // 最热
        self.hotOrnew = 2;
        // 页数的初始值再设置为1
        self.collectionNextCursor = 1;
        [self getCollectionViewData];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
